package com.pw.study.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @Author: linux_future
 * @since: 2022/3/30
 **/
public class TcpServerV2 {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(6666);
        System.out.println("server running。。。。");
        for (; ; ) {
            Socket accept = server.accept();
            System.out.println(accept.getRemoteSocketAddress());
            Thread t = new Handler(accept);
            t.start();
        }
    }

    static class Handler extends Thread {
        Socket socket;

        public Handler(Socket sock) {
            this.socket = sock;
        }

        @Override
        public void run() {
            try (InputStream in = socket.getInputStream()) {
                try (OutputStream out = socket.getOutputStream()) {
                    msgHandler(in, out);
                }
            } catch (IOException e) {
                try {
                    this.socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                System.out.println("client disconnected ...");
            }
        }

        private void msgHandler(InputStream in, OutputStream out) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
            writer.write("server --> client ..\n");
            writer.flush();
            for (; ; ) {
                String str = reader.readLine();
                System.out.println("server receive:  " + str);
                if ("bye".equals(str)) {
                    writer.write("bye client ...");
                    writer.flush();
                    break;
                }
                writer.write("ok: " + str + " \n");
                writer.flush();
            }

        }
    }

}
